<?php

namespace App\HttpController\Admin;

use App\Model\CategorysModel;
use Carbon\Carbon;

class CategoryController extends AuthController{


    public function index(){
        $request = $this->request();
        $page = $request->getRequestParam('page') ?: 1;
        $kwd = trim($request->getRequestParam('kwd')) ?: '';
        $model = new CategorysModel();
        $list = $model->where(function ($query) use($kwd){
                if($kwd) $query->whereLike('name',$kwd);
            })->orderBy('created_at')
            ->paginate($page,8);
        return $this->writeJson(0,$list);
    }


    public function update(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $model = new CategorysModel();
        if($data['id']){
            //修改
            $model->update($data);
            return $this->writeJson(0,null,'编辑成功');
        }else{
            //新增
            $data['created_at'] = Carbon::now();
            $model->create($data);
            return $this->writeJson(0,null,'新增成功');
        }
    }


    public function destroy(){
        $request = $this->request();
        $id = $request->getRequestParam('id');
        $model = new CategorysModel();
        if(is_array($id)){
            $model->whereIn('id',$id)->delete();
        }else{
            $model->destroy($id);
        }
        return $this->writeJson(0);
    }

}
